package com.example.order.controller;

import com.example.order.model.dto.CreateOrderRequest;
import com.example.order.model.dto.OrderResponse;
import com.example.order.service.OrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 订单控制器
 * 提供订单相关的 REST API
 * 
 * @author mall-team
 */
@Slf4j
@RestController
@RequestMapping("/api/orders")
@RequiredArgsConstructor
public class OrderController {

    private final OrderService orderService;

    /**
     * 创建订单
     * POST /api/orders
     * 
     * @param request 创建订单请求
     * @return 订单响应
     */
    @PostMapping
    public ResponseEntity<OrderResponse> createOrder(@RequestBody CreateOrderRequest request) {
        log.info("接收到创建订单请求: userId={}", request.getUserId());
        
        try {
            OrderResponse response = orderService.createOrder(request);
            return ResponseEntity.status(HttpStatus.CREATED).body(response);
        } catch (Exception e) {
            log.error("创建订单失败: {}", e.getMessage(), e);
            throw new RuntimeException("创建订单失败: " + e.getMessage());
        }
    }

    /**
     * 根据订单编号查询订单
     * GET /api/orders/{orderNo}
     * 
     * @param orderNo 订单编号
     * @return 订单响应
     */
    @GetMapping("/{orderNo}")
    public ResponseEntity<OrderResponse> getOrder(@PathVariable String orderNo) {
        log.info("查询订单: orderNo={}", orderNo);
        
        try {
            OrderResponse response = orderService.getOrderByOrderNo(orderNo);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("查询订单失败: orderNo={}, error={}", orderNo, e.getMessage(), e);
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 健康检查接口
     * GET /api/orders/health
     * 
     * @return 健康状态
     */
    @GetMapping("/health")
    public ResponseEntity<String> health() {
        return ResponseEntity.ok("Order Service is running");
    }
}

